"""Wraps the networking for use with the GUI"""

from recommend import GetRecommendedProfile
from downloaders import downloadElements, addElements
from displayWidget import TrayDisplay

from PyQt4 import QtGui

def addIntoTool(toolbar, tabDisplay, profiles, tableDisplay, musicPlayer):
    """Adds the network actions into the toolbar"""
    rec=Recommender(tabDisplay, profiles, tableDisplay, musicPlayer)
    toolbar.addAction(QtGui.QIcon('icons/recommend.png'),
                      'Recommend Songs', rec)

class Recommender(object):
    """Used to get the recommended profile, and then add it in"""
    def __init__(self, tabDisplay, profiles, tableDisplay, musicPlayer):
        self.__tabDisplay=tabDisplay
        self.__profiles=profiles
        self.__running=False
        self.__listener=RecommendedListener(tableDisplay, musicPlayer)
    def __call__(self):
        if not self.__running:
            elements, peers, profileName=self.__getDetails()
            profile=self.__profiles[profileName]
            GetRecommendedProfile(elements, peers, profile, profileName,
                                  self.__finish)
            self.running=True
    def __finish(self, recommendedProfile):
        """Finishes the recommendation by inserting the profile and becomes
        ready to accept calls again"""
        trayDisplay=TrayDisplay(recommendedProfile, self.__tabDisplay)
        trayDisplay.tableWidget.listener=self.__listener
        self.__tabDisplay.addWidget('Recommended Songs', trayDisplay)
        self.__running=False
    def __getDetails(self):
        """Return the details required for getting a recommendation"""
        #Using default values now
        return (self.__profiles['Songs'].elements,
                self.__profiles['Peers'].elements,
                'Songs')

class RecommendedListener(object):
    """Listens to the recommended profile"""
    def __init__(self, tableDisplay, musicPlayer):
        self.__tableDisplay=tableDisplay
        self.__musicPlayer=musicPlayer
    def loadElements(self, elements, selectedp):
        if not selectedp: elements=[elements[0]]
        addElements(self.__tableDisplay, elements)
    def alternateAction(self, elements, selectedp):
        if not selectedp: elements=elements.next() #Takes the first element of the iterator
        downloadElements(elements, self.__musicPlayer)
